import React, { useEffect } from 'react';
import { connect } from 'dva';
import { Redirect } from 'umi';
import { PageLoading } from '@/components';
import { setToken } from '@/utils/authority';

const errorFn = (e) => {
  const tag = e.target.localName;
  if (tag === 'link') {
    const baseUrl = e?.target?.href ?? '';
    if (baseUrl.includes('gw-ams.com/saas')) {
      window.location.reload();
    }
  }
};

const SecurityLayout = (props) => {
  const { children, dispatch, isLogin, loading, location } = props;

  /* const chatbotButton = document.getElementById('fastgpt-chatbot-button');
  const chatbotWindow = document.getElementById('fastgpt-chatbot-window');
  const eye1 = document.createElement('div');
  const eye2 = document.createElement('div');

  const setDisplay = (element, display) => {
    if (element) {
      element.style.setProperty('display', display, 'important');
    }
  }; */

  useEffect(() => {
    dispatch?.({ type: 'user/fetchCurrent' });
    window.addEventListener('error', errorFn, true);
    return () => {
      window.removeEventListener('error', errorFn);
    };
  }, []);

  /* useEffect(() => {
    let changeCount = 0;
    const img = chatbotButton?.querySelector('img');

    if (isLogin) {
      setDisplay(chatbotButton, 'block');
      setDisplay(chatbotWindow, 'block');
      if (chatbotWindow) {
        chatbotWindow.style.right = '109.5px';
        chatbotWindow.style.bottom = '30.3334px';
      }
      if (!chatbotButton.querySelector('.eye')) {
        eye1.className = 'eye';
        eye2.className = 'eye';
        chatbotButton.appendChild(eye1);
        chatbotButton.appendChild(eye2);
      }
      const observer = new MutationObserver((mutations) => {
        mutations.forEach((mutation) => {
          if (mutation.attributeName === 'src') {
            changeCount++;
            if (changeCount % 2 === 1) {
              eye1.style.display = 'none';
              eye2.style.display = 'none';
            } else {
              eye1.style.display = 'block';
              eye2.style.display = 'block';
            }
          }
        });
      });

      observer.observe(img, { attributes: true, attributeFilter: ['src'] });

      return () => {
        observer.disconnect();
      };
    } else {
      setDisplay(chatbotButton, 'none');
      setDisplay(chatbotWindow, 'none');
    }
  }, [isLogin]); */

  // You can replace it to your authentication rule (such as check token exists)
  // 你可以把它替换成你自己的登录认证规则（比如判断 token 是否存在）
  const isExternalLink = location?.query?.access_token;
  if (isExternalLink) {
    const { form_key, id } = location?.query;
    setToken(isExternalLink);
    return <Redirect to={`${location.pathname}?form_key=${form_key}&id=${id}`} />;
  }
  if (!isLogin || loading) return <PageLoading />;
  if (!isLogin) return <Redirect to={`/user/login`} />;
  return <>{children}</>;
};

export default connect(({ user }) => ({
  isLogin: !!user?.currentUser?.personId,
  loading: user.isLoading,
}))(SecurityLayout);
